<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    :showOkBtn="props.info.type !== 'look'"
    :defaultFullscreen="props.isDefaultFullscreen"
    :cancelText="props.info.type !== 'look' ? '取消' : '关闭'"
    okText="提交"
    @register="register"
    :title="modalTitle"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModal } from '/@/components/Modal';
  import { computed, toRef, nextTick } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { getFormErrorMessage } from '/@/utils/index';

  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
    schemasProps: {
      type: Array,
      default: () => [],
    },
    isDefaultFullscreen: {
      type: Boolean,
      default: () => false,
    },
  });
  let modalTitle = computed(() => {
    return `${props.info.type === 'add' ? '新增' : props.info.type === 'update' ? '编辑' : '查看'}`;
  });
  let schemasPro: FormSchema[] = props.schemasProps as FormSchema[];

  const [registerForm, { setProps, validateFields, resetFields, setFieldsValue, clearValidate }] =
    useForm({
      labelWidth: 150,
      schemas: schemasPro,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 24,
      },
    });

  const emit = defineEmits(['handleSubmit']);
  const [register] = useModal();
  async function handleSubmint() {
    try {
      let res = await validateFields();
      emit('handleSubmit', res);
    } catch (error) {
      console.log('not passing', error);
      getFormErrorMessage(error);
    }
  }
  function initData() {
    let info = toRef(props, 'info');
    let params = info.value.data;
    setFieldsValue(params);
    if (props.info.type === 'look') {
      setProps({ disabled: true });
      clearValidate();
    }
  }
  function handleVisibleChange(visible) {
    if (visible) {
      if (props.info.type !== 'add') {
        nextTick(() => {
          initData();
        });
      }
    } else {
      resetFields();
      setProps({ disabled: false });
    }
  }
</script>

<style lang="less" scoped></style>
